package com.naizhuai.ui.user.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.naizhuai.MainActivity;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.apistoreiml.CommonManagerIml;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.entity.JumpBean;
import com.naizhuai.ui.user.UpdatePasswordActivity;
import com.naizhuai.ui.user.register.RegisterActivity;
import com.naizhuai.util.ValidateUtil;
import com.naizhuai.util.ViewUtils;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;

public class LoginActivity extends BaseActivity implements LoginContract.View {


    public static void start(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    public static void exitLoginstart(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
        AccountHelper.logout();
    }

    //    @BindView(R.id.img_backgroud)
//    ImageView img_backgroud;
    @BindView(R.id.new_user_register)
    TextView new_user_register;
    //    @BindView(R.id.txt_welcome)
//    TextView txt_welcome;
    @BindView(R.id.ed_phonenumber)
    EditText ed_phonenumber;
    @BindView(R.id.ed_password)
    EditText ed_password;
    @BindView(R.id.btn_login)
    Button btn_login;
    @BindView(R.id.forget_password)
    TextView forget_password;
    @BindView(R.id.password_visibility)
    ImageView passwordVisibility;

    private LoginContract.Presenter mLoginPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login1;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        if (AccountHelper.isLogin()) {
            loginSuccess();
        } else {
            InitView();
            InitSomething();
            InitPresenter();
//            ed_phonenumber.setText("18926481709");
//            ed_password.setText("123456");
        }
    }

    private void InitPresenter() {
        mLoginPresenter = new LoginPresenter();
        mLoginPresenter.takeView(this);
    }

    private void InitSomething() {
        new_user_register.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivityTransition(intent);
        });
//        ed_phonenumber.addTextChangedListener(new CustomTextWatch() {
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                changeBtnState();
//                //当输入号码复合手机号形式以后 查询本地数据库的数据 得到名称和头像
//                if (ValidateUtil.validateMobile(s.toString())) {
//                    mLoginPresenter.searchLocalUser(s.toString());
//                } else {
//                    txt_welcome.setText(getText(R.string.welcome_use));
//                    user_head_img.setImageResource(R.drawable.ic_default_avatar_toolbar);
//                }
//            }
//        });
//        ed_password.addTextChangedListener(new CustomTextWatch() {
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                changeBtnState();
//            }
//        });

        passwordVisibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passwordVisibility.setSelected(!passwordVisibility.isSelected());
                if (passwordVisibility.isSelected()){
                    ed_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
                }else{
                    ed_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });

        btn_login.setOnClickListener(v -> {
            String changenumber = ed_phonenumber.getText().toString().trim();
            String changepassword = ed_password.getText().toString().trim();
            // 正则判断手机号的格式
            if (!ValidateUtil.validateMobile(changenumber)) {
                shortToast(getString(R.string.phone_format_error));
                setShakeAnimation(ed_phonenumber);
                return;
            }
            if (changepassword.length() < 6) {
                shortToast(getString(R.string.password_length));
                setShakeAnimation(ed_password);
                return;
            }
            mLoginPresenter.userLogin(changenumber, changepassword);
        });
        forget_password.setOnClickListener(v -> {
            if (TextUtils.isEmpty(ViewUtils.text(ed_phonenumber))) {
                shortToast(getString(R.string.please_phonenumber));
                return;
            }
            UpdatePasswordActivity.start(LoginActivity.this, ViewUtils.text(ed_phonenumber));
        });
    }

//    private void changeBtnState() {
//        String changenumber = ed_phonenumber.getText().toString().trim();
//        String changepassword = ed_password.getText().toString().trim();
//        if (!TextUtils.isEmpty(changenumber) &&
//                !TextUtils.isEmpty(changepassword)) {
//            btn_login.setEnabled(true);
//        } else {
//            btn_login.setEnabled(false);
//        }
//    }


//    private void startImgAnim() {
//        if (animation == null) {
//            animation = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.translate_anim);
//            img_backgroud.startAnimation(animation);
//        }
//
//    }

    private void InitView() {
//        img_backgroud = findViewById(R.id.img_backgroud);
//        user_head_img = findViewById(R.id.user_head_img);
//        new_user_register = findViewById(R.id.new_user_register);
//        txt_welcome = findViewById(R.id.txt_welcome);
//        ed_phonenumber = findViewById(R.id.ed_phonenumber);
//        ed_password = findViewById(R.id.ed_password);
//        btn_login = findViewById(R.id.btn_login);
//        forget_password = findViewById(R.id.forget_password);
    }

    @Override
    public void loginSuccess() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void loginFail(String errormsg) {
        shortToast(errormsg);
    }

    @Override
    public void userExist(String username, String imgurl) {
//        txt_welcome.setText(getString(R.string.welcome_person,username));
//        user_head_img.post(() -> user_head_img.setImageDrawable(DrawableUtils.setTextDrawable(username)));

    }

    @Override
    public void showPhoneError() {

    }

    @Override
    public void saveUidSid(String uid, String sid) {
        AccountHelper.login(uid, sid);
    }

    @Override
    public void showLoading(boolean state) {
        if (state) {
            showWaitDialog(getString(R.string.Logining));
        } else {
            hideWaitDialog();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoginPresenter != null)
            mLoginPresenter.dropView();
    }

    @Override
    public void onlyTest(String phoneNumber) {
        CommonManagerIml.getInstance().user_report(JPushInterface.getRegistrationID(this), JumpBean.login)
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {

                    }

                    @Override
                    protected void onSuccess(String result) {

                    }
                });
    }

    @Override
    public void onBackPressed() {
        if (isWaitDialogShowing1()) {
            mLoginPresenter.cancelRequest();
            hideWaitDialog();
        } else {
            super.onBackPressed();
        }
    }


    private void setShakeAnimation(View view) {
        view.startAnimation(shakeAnimation());
    }

    /**
     * 晃动动画
     * 默认晃动三下
     *
     * @return
     */
    public static Animation shakeAnimation() {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(3));
        translateAnimation.setDuration(500);
        return translateAnimation;
    }
}
